<template>
  <div class="flex-1 h-full card_class">
    <div class="card_title">
      <span>{{ title }}</span>
      <div>
        <el-select
          v-model="searchParam.year"
          placeholder="请选择"
          filterable
          :suffixIcon="() => '年'"
          class="w-[70px] mr-[10px]"
          size="small"
          @change="startSearch"
        >
          <el-option
            v-for="item in useDictionary('YearList')"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="searchParam.month"
          placeholder="请选择"
          filterable
          :suffixIcon="() => '月'"
          class="w-[50px]"
          :class="!panelSetIcon ? 'mr-[20px]' : ''"
          size="small"
          @change="startSearch"
        >
          <el-option
            v-for="item in useDictionary('MonthList')"
            :key="item.value"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>
    <div class="echarts" style="height: calc(100% - 50px)">
      <!-- <div
        class="text-[16px] h-[10%] lh-[10%] font-700 flex justify-center items-center"
      >
        <span class="pt-[0px]">生产重量0吨</span>
      </div> -->
      <div class="flex" style="height: calc(100% - 0%)">
        <div class="flex-1">
          <div class="flex items-center h-[10%] justify-center mt-[10px]">
            <!-- <span
              class="text-[14px]"
              :class="isDarkMode(routeName) ? 'color-[#eee] text-[15px]!' : ''"
              >HT、QT重量比例</span
            > -->
            <el-radio-group
              v-model="radio_l"
              size="small"
              fill="#006DFB"
              class="ml-[10px]"
              @change="handleSearch"
            >
              <el-radio-button
                v-for="item in selectOption_l"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
          <ECharts
            v-if="option"
            :option="option"
            :id="`ProductionPolishAnalysis_l` + props.id"
            ref="chart"
            style="height: calc(100% - 10% - 10px)"
          />
        </div>
        <div class="flex-1">
          <div class="flex items-center h-[10%] justify-center mt-[10px]">
            <!-- <span
              class="text-[14px]"
              :class="isDarkMode(routeName) ? 'color-[#eee] text-[15px]!' : ''"
              >HT、QT数量比例</span
            > -->
            <el-radio-group
              v-model="radio_r"
              size="small"
              fill="#006DFB"
              class="ml-[10px]"
              @change="handleSearch1"
            >
              <el-radio-button
                v-for="item in selectOption_r"
                :key="item.value"
                :label="item.value"
              >
                {{ item.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
          <ECharts
            v-if="option1"
            :option="option1"
            :id="`ProductionPolishAnalysis_r` + props.id"
            ref="chart1"
            style="height: calc(100% - 10% - 10px)"
          />
        </div>
      </div>
    </div>
    <i-ep-close
      v-show="!panelSetIcon"
      class="el-icon-close"
      style="float: right; padding: 3px 0"
      @click="deletePanelItem"
    />
  </div>
</template>

<script lang="ts" setup>
import dayjs from "dayjs";
import request from "@/utils/request";
import { useDictionary } from "@/utils/useTable";
import {
  qmsWeightProductList,
  qmsWeightProductOtherList,
} from "@/assets/js/qms";
import * as echarts from "echarts";
import { useRoute } from "vue-router";
import { isDarkMode } from "@/utils/index";
import { fontWeight } from "html2canvas/dist/types/css/property-descriptors/font-weight";
const routeName = useRoute().name;
const emit = defineEmits(["deletePanelItemEvent"]);

const props = defineProps({
  panelSetIcon: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  url: {
    type: String,
    default: () => {
      return "";
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  params: {
    type: Object,
    default: () => {
      return {};
    },
  },
});
const { panelSetIcon, id, url, title } = toRefs(props);

const selectOption_l = [
  {
    label: "重量",
    value: "4",
  },
  {
    label: "炉数",
    value: "2",
  },
];
const selectOption_r = [
  {
    label: "炉数",
    value: "2",
  },
  {
    label: "重量",
    value: "4",
  },
  {
    label: "工时",
    value: "6",
  },
];

const radio_l = ref("4");
const radio_r = ref("2");

const rich: any = {
  name: {
    color: "#666",
    fontSize: 13,
    // padding: [8, 30, 0, 30],
    fontWeight: "600",
    align: "left",
  },
  value: {
    color: "#333",
    fontSize: 14,
    padding: [0, 30, 8, 30],
    fontWeight: "500",
    align: "left",
  },
  percent: {
    color: "#FFF",
    align: "right",
    fontSize: 14,
    fontWeight: "400",
    //padding: [0, 5]
  },
};
//职称结构图表
const colorList = [
  "#006DFB",
  "#18dcff",
  "#313ca9",
  "#B4EC51",
  "#7d5fff",
  "#FFBC6D",
  "#51D9A2",
  "#f9e264",
  "#f47a75",
  "grey",
  new echarts.graphic.LinearGradient(0, 1, 0, 0, [
    {
      offset: 0,
      color: "#04B9BD",
    },
    {
      offset: 1,
      color: "#76F2F8",
    },
  ]),
  "#765025",
];
const colorList1 = [
  "#bf19ff",
  "#854cff",
  "#5f45ff",
  "#02cdff",
  "#314976",
  "#f9e264",
  "#f47a75",
  "#009db2",
  "#024b51- 0780cf",
  "#765005",
];

function deletePanelItem() {
  emit("deletePanelItemEvent", id.value);
}

const reportData = ref();
const reportDataOther = ref();

const title_l = ref("");
const title_r = ref("");

const searchParam = reactive({
  year: dayjs().year().toString(),
  month: (dayjs().month() + 1).toString(),
});

const searchedParam = reactive({
  year: dayjs().year().toString(),
  month: (dayjs().month() + 1).toString(),
});

async function handleSearch() {
  reportData.value = null;
  loading.value = true;
  Object.assign(searchedParam, searchParam);
  const { data } = await request({
    url: `/mes/mesplanstatistics/queryBurnishOutsideCake`,
    method: "post",
    data: {
      statisticsYear: searchParam.year,
      statisticsMoon: searchParam.month,
      statisticsState: radio_l.value,
    },
  }).finally(() => {
    loading.value = false;
  });
  reportData.value = data.data;
  title_l.value = data.name;
  //   reportData.value = qmsWeightProductList;
  setOptions();
}
async function handleSearch1() {
  reportDataOther.value = null;
  loading.value = true;
  Object.assign(searchedParam, searchParam);
  const { data } = await request({
    url: `/mes/mesplanstatistics/queryBurnishWithinCake`,
    method: "post",
    data: {
      statisticsYear: searchParam.year,
      statisticsMoon: searchParam.month,
      statisticsState: radio_r.value,
    },
  }).finally(() => {
    loading.value = false;
  });
  reportDataOther.value = data.data;
  title_r.value = data.name;
  //   reportDataOther.value = qmsWeightProductOtherList;

  setOptions1();
}

const option = ref();
const xAxis = ref<string[]>([]);
const yAxis = ref<number[]>([]);
const xAxisOther = ref<string[]>([]);
const yAxisOther = ref<number[]>([]);
const titleSize = isDarkMode(routeName) ? 15 : 14;
const chart = ref();
function setOptions() {
  const rawData = reportData.value;
  // 对数据进行降序排序
  rawData.sort((a, b) => b.value - a.value);

  rawData?.map((e: any, index) => {
    xAxis.value = [...xAxis.value, e.name];
    yAxis.value = [...yAxis.value, e.value];
  });

  option.value = {
    color: colorList,
    darkMode: true,
    layout: "none",
    animation: true, //控制动画示否开启
    animationDuration: 3000,
    animationEasing: "bounceOut", //缓动动画
    animationThreshold: 8, //动画元素的阈值
    backgroundColor: "transparent", // 给echarts图设置背景色
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(0,0,0,.5)",
      textStyle: {
        color: "#fff",
        fontFamily: "DINLight",
        fontSize: 14,
      },
    },
    grid: {
      left: "3%", //图表距边框的距离
      right: "3%",
      top: "8%",
      bottom: "4%",
      containLabel: true,
    },
    title: [
      {
        show: true,
        text: title_l.value,
        left: "center",
        top: "7%",
        // textAlign: "center",
        textStyle: {
          fontSize: titleSize,
          color: isDarkMode(routeName) ? "rgb(255,255,255)" : "#333",
        },
      },
    ],
    avoidLabelOverlap: false, // 避免标签重叠
    series: [
      {
        itemStyle: {
          color: function (params) {
            return colorList[params?.dataIndex];
          },
        },
        type: "pie",
        radius: ["0%", "80%"],
        center: ["50%", "56%"],
        avoidLabelOverlap: false, // 避免标签重叠
        label: {
          show: true,
          position: "inner",
          //formatter: "{b}:{c}\n{d}%",
          formatter: function (params) {
            var d = Math.round(params.percent); // 取整数
            return (
              "{b|" +
              params.name +
              "}：{c|" +
              params.value +
              "}\n{d|" +
              d +
              "%}"
            );
          },
          fontSize: isDarkMode(routeName) ? 13 : 13,
          fontWeight: 700,
          lineHeight: 16,

          rich: rich,
        },
        labelLine: {
          show: false,
          length: 20,
          length2: 10,
          lineStyle: {
            width: 1,
          },
        },
        data: reportData.value,
      },
      //   {
      //     itemStyle: {
      //       color: isDarkMode(routeName) ? "" : "#F2F9F7",
      //       opacity: "0.3",
      //       // color: "#F2F9F7",
      //     },
      //     type: "pie",
      //     silent: true, // 取消高亮
      //     radius: ["0%", "75%"],
      //     center: ["50%", "56%"],
      //     data: reportData.value,
      //     label: {
      //       show: false,
      //       position: "inner",
      //       formatter: (params: any) => {
      //         return "{percent|" + params.percent.toFixed(0) + "%}";
      //       },
      //       rich: rich,
      //     },
      //     z: -1,
      //   },
    ],
  };
}

const option1 = ref();
function setOptions1() {
  const rawData = reportDataOther.value;
  // 对数据进行降序排序
  rawData.sort((a, b) => b.value - a.value);

  rawData?.map((e: any, index) => {
    xAxis.value = [...xAxis.value, e.name];
    yAxis.value = [...yAxis.value, e.value];
  });

  option1.value = {
    // 全局文字样式（影响标题、图例、标签等）
    textStyle: {
      color: isDarkMode(routeName) ? "#fff" : "#767676", // 统一字体颜色
    },
    color: colorList,
    darkMode: true,
    layout: "none",
    animation: true, //控制动画示否开启
    animationDuration: 3000,
    animationEasing: "bounceOut", //缓动动画
    animationThreshold: 8, //动画元素的阈值
    backgroundColor: "transparent", // 给echarts图设置背景色
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(0,0,0,.5)",
      textStyle: {
        color: "#fff",
        fontFamily: "DINLight",
        fontSize: 14,
      },
    },
    grid: {
      left: "0%", //图表距边框的距离
      right: "0%",
      top: "8%",
      bottom: "4%",
      containLabel: true,
    },
    title: [
      {
        show: true,
        text: title_r.value,
        left: "center",
        top: "7%",
        // textAlign: "center",
        textStyle: {
          fontSize: titleSize,
          color: isDarkMode(routeName) ? "rgb(255,255,255)" : "#333",
        },
      },
    ],
    series: [
      {
        itemStyle: {
          color: function (params) {
            return colorList[params?.dataIndex];
          },
        },
        type: "pie",
        radius: ["0%", "80%"],
        center: ["50%", "56%"],
        label: {
          show: true,
          position: "inside",
          //   formatter: "{name|{b}}，{d}%",
          //formatter: "{b}:{c}\n{d}%",
          formatter: function (params) {
            var d = Math.round(params.percent); // 取整数
            return (
              "{b|" +
              params.name +
              "}：{c|" +
              params.value +
              "}\n{d|" +
              d +
              "%}"
            );
          },
          //   color: isDarkMode(routeName) ? "#eeeeee" : "#666",
          fontSize: isDarkMode(routeName) ? 13 : 13,
          fontWeight: 700,
          lineHeight: 20,
          rich: rich,
        },
        labelLine: {
          show: false,
          length: 20,
          length2: 10,
          lineStyle: {
            width: 1,
          },
        },
        data: reportDataOther.value,
      },
      //   {
      //     itemStyle: {
      //       color: isDarkMode(routeName) ? "" : "#F2F9F7",
      //       opacity: "0.3",
      //       // color: "#F2F9F7",
      //     },
      //     type: "pie",
      //     silent: true, // 取消高亮
      //     radius: ["0%", "75%"],
      //     center: ["50%", "56%"],
      //     data: reportDataOther.value,
      //     label: {
      //       show: false,
      //       position: "inner",
      //       formatter: (params: any) => {
      //         return "{percent|" + params.percent.toFixed(0) + "%}";
      //       },
      //       rich: rich,
      //     },
      //     z: -1,
      //   },
    ],
  };
}

const loading = ref(false);

function startSearch() {
  handleSearch();
  handleSearch1();
}
onMounted(() => {
  handleSearch();
  handleSearch1();
  window.addEventListener("session-storage-updated", onSessionStorageChange);
});

onBeforeUnmount(() => {
  window.removeEventListener("session-storage-updated", onSessionStorageChange);
});

function onSessionStorageChange(event: any) {
  if (event.key === "month") {
    searchParam.month = JSON.parse(sessionStorage.getItem("month"));
    handleSearch();
    handleSearch1();
  }
  if (event.key === "year") {
    searchParam.year = JSON.parse(sessionStorage.getItem("year"));
    handleSearch();
    handleSearch1();
  }
}
</script>

<style lang="scss" scoped>
.card_class {
  background-color: var(--el-bg-color-overlay);
  border-radius: 4px;
  box-shadow: 0px 0px 12px rgba(3, 8, 72, 0.08);
  .card_title {
    white-space: nowrap;
    font-size: 20px;
    color: #333;
    font-family: YOUSHE;
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
